package com.linchong.concurrency.basic;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2022-04-10 9:46
 * @Description: ConcurrencyExample$
 */
@Slf4j
@NotThreadSafe
public class ConcurrencyExample {


	public  static int clientTotal = 5000;
	public  static int threadTotal = 200;
	public static int count = 0;

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executorService = Executors.newCachedThreadPool();
		final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
		final Semaphore semaphore = new Semaphore(threadTotal);
		for (int i = 0; i < clientTotal; i++) {
			executorService.execute(()->{
				try {
					semaphore.acquire();
					add();
					semaphore.release();
				} catch (InterruptedException e) {
					log.error("Exception",e.getMessage());
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		executorService.shutdown();
		log.info("count:{}",count);
	}


	public static void add(){
		count++;
	}
}
